package com.dbsop.domain.rest.agg;

import com.dbsop.common.enums.Order;
import com.dbsop.domain.rest.AggTransportOperation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.TopHitsAggregationBuilder;
import org.elasticsearch.search.sort.SortOrder;

import java.util.LinkedHashSet;
import java.util.Set;

public final class TopHits extends RestAgg implements AggTransportOperation {
    private String [] fields = null;


    private Set<String> fieldSet = new LinkedHashSet<>();


    public void addField(String field){
        fieldSet.add(field);
    }


    private int num = 1;

    private Order order  = null;

    public TopHits(String fieldName,Order order,Integer num) {
        super(fieldName);
        this.order = order;
        if (num != null && num >0){
            this.num = num;
        }
    }

    @Override
    public AggregationBuilder aggregationBuilder() {
        TopHitsAggregationBuilder topHitsAggregationBuilder = null;
        if (order ==Order.ASC){
            topHitsAggregationBuilder= new TopHitsAggregationBuilder(formatName).sort(fieldName, SortOrder.ASC);
        }else if (order == Order.DESC){
            topHitsAggregationBuilder= new TopHitsAggregationBuilder(formatName).sort(fieldName, SortOrder.DESC);
        }
        topHitsAggregationBuilder.size(num);
        if (fieldSet.size()>0){
            fields = new String[fieldSet.size()];
            int i = 0 ;
            for (String field : fieldSet) {
                this.fields[i] = field;
                i++;
            }
            topHitsAggregationBuilder.fetchSource(fields,null);
        }
        return topHitsAggregationBuilder;
    }
}
